# gozerbot/myimport.py
#
#

""" use the imp module to import modules. """

__status__ = "seen"

##  gozerbot import

from gozerbot.utils.log import rlog
from gozerbot.utils.locking import lockdec

## basic imports

import time
import sys
import imp
import os
import thread

## locks

gozerimportlock = thread.allocate_lock()
locked = lockdec(gozerimportlock)

## gozer_import function

def gozer_import(name, path=None):

    """
        import module <name> with the imp module  .. will reload module is 
        already in sys.modules.

    """
    rlog(3, 'gozerimport', 'importing %s' % name)
    splitted = name.split('.')
    for plug in splitted:
        fp, pathname, description = imp.find_module(plug, path)
        try:
           result = imp.load_module(plug, fp, pathname, description)
           try: path = result.__path__
           except: pass
        finally:
            if fp: fp.close()
    if result: return result

## force_import function

def force_import(name):
    """ force import of module <name> by replacing it in sys.modules. """
    try: del sys.modules[name]
    except KeyError: pass
    plug = gozer_import(name)
    if plug: sys.modules[name] = plug ; return plug
